package guavatest.caches;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;

import java.util.concurrent.*;

/**
 * @Auther     : yxpweb
 * @Date       : 2021/8/10 18:36
 * @Description: 重置数据refreshAfterWrite
 */
public class CacheLoadTest {
    // 每4s 重置一次数据
    private static final LoadingCache<Long, IntHolder> rateLimiter =
            CacheBuilder.newBuilder().refreshAfterWrite(4, TimeUnit.SECONDS).maximumSize(10000)
                    .build(new CacheLoader<Long, IntHolder>() {
                        @Override
                        public IntHolder load(Long key) throws Exception {
                            return new IntHolder(200);
                        }

                        @Override
                        public ListenableFuture<IntHolder> reload(Long key, IntHolder oldValue) throws Exception {
                            oldValue.setValue(200);
                            return Futures.immediateFuture(oldValue);
                        }
                    });

    public static void main(String[] args) throws ExecutionException {
        IntHolder intHolder = rateLimiter.get(100l);
        int value = intHolder.getValue();
        System.out.println(value);
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        intHolder.setValue(54);
        executorService.scheduleAtFixedRate(() -> {
            IntHolder intHolder1 = null;
            try {
                intHolder1 = rateLimiter.get(100l);
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            System.out.println(intHolder1.getValue());
        }, 1, 1, TimeUnit.SECONDS);
    }
}
